<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时聊天应用 - 用户列表</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .user-list-height {
                height: calc(100vh - 4rem);
            }
        }
    </style>
</head>
<body class="bg-gray-100 font-sans text-gray-800">
<!-- 用户用户列表页面
展示所有可聊天的用户，点击用户可进入聊天界面
顶部显示当前登录用户信息和退出按钮
-->
<div id="user-list-page" class="h-screen flex flex-col bg-light">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm py-3 px-6 flex justify-between items-center">
        <h1 class="text-xl font-bold text-dark">用户列表</h1>
        <div class="flex items-center gap-2">
            <span id="current-user-name" class="text-gray-600"></span>
            <button id="logout-btn" class="text-gray-500 hover:text-red-500 transition-colors">
                <i class="fa fa-sign-out"></i>
            </button>
        </div>
    </header>

    <!-- 用户列表 -->
    <div class="overflow-y-auto user-list-height px-4 py-2">
        <div id="user-list" class="space-y-2 mt-2">
            <!-- 用户项将通过JS动态添加 -->
            <div class="text-center text-gray-500 py-4">
                <i class="fa fa-spinner fa-spin mr-2"></i>加载用户列表中...
            </div>
        </div>
    </div>
</div>

<script>
    // 全局变量
    const BACK_ADDRESS_PORT = '47.121.204.23:8081';
    let token = localStorage.getItem('token');
    let currentUserId = localStorage.getItem('currentUserId');
    let currentUserName = localStorage.getItem('currentUserName');

    // DOM元素
    const userList = document.getElementById('user-list');
    const currentUserNameEl = document.getElementById('current-user-name');
    const logoutBtn = document.getElementById('logout-btn');

    // 页面初始化
    document.addEventListener('DOMContentLoaded', () => {
        // 检查是否已登录
        if (!token || !currentUserId) {
            // 未登录，跳转到登录页面
            window.location.href = 'login.html';
            return;
        }

        // 显示当前登录用户名
        currentUserNameEl.textContent = currentUserName || '用户';

        // 获取用户列表
        fetchUserList();

        // 事件监听
        logoutBtn.addEventListener('click', handleLogout);
    });

    // 登出处理
    function handleLogout() {
        // 清除本地存储
        localStorage.removeItem('token');
        localStorage.removeItem('currentUserId');
        localStorage.removeItem('currentUserName');

        // 跳转到登录页面
        window.location.href = 'login.html';
    }

    // 获取用户列表
    async function fetchUserList() {
        if (!token) return;

        try {
            const response = await fetch('http://' + BACK_ADDRESS_PORT + '/user/getUserList', {
                method: 'GET',
                headers: {
                    'Authorization': token
                }
            });

            const result = await response.json();

            if (response.ok && Array.isArray(result.data)) {
                // 过滤掉当前登录用户
                const users = result.data.filter(user => user.name !== currentUserName);
                renderUserList(users);
            } else {
                console.error('获取用户列表失败:', result.message);
                userList.innerHTML = '<div class="text-center text-red-500 py-4">获取用户列表失败</div>';
                // 令牌可能无效，一段时间后跳转到登录页
                setTimeout(handleLogout, 3000);
            }
        } catch (error) {
            console.error('获取用户列表失败:', error);
            userList.innerHTML = '<div class="text-center text-red-500 py-4">网络错误，无法获取用户列表</div>';
        }
    }

    // 渲染用户列表
    function renderUserList(users) {
        userList.innerHTML = '';

        if (users.length === 0) {
            userList.innerHTML = '<div class="text-center text-gray-500 py-4">没有其他用户在线</div>';
            return;
        }

        // 遍历用户列表并创建用户项
        users.forEach(user => {
            const userItem = document.createElement('div');
            userItem.className = 'bg-white rounded-lg p-3 shadow-sm hover:shadow-md transition-all duration-200 cursor-pointer flex items-center justify-between transform hover:translate-x-1';
            userItem.innerHTML = `
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                        <i class="fa fa-user"></i>
                    </div>
                    <span class="font-medium">${user.name}</span>
                </div>
                <i class="fa fa-chevron-right text-gray-400"></i>
            `;

            // 点击用户项进入聊天页面
            userItem.addEventListener('click', () => {
                // 保存目标用户信息到本地存储
                localStorage.setItem('targetUserId', user.id);
                localStorage.setItem('targetUserName', user.name);
                // 跳转到聊天页面
                window.location.href = 'chat.html';
            });

            userList.appendChild(userItem);
        });
    }
</script>
</body>
</html>
